var express = require('express');
var router = express.Router();

let userService = require("../service/userinfoService");

let crypto = require("crypto");//加密

let jwt = require("jsonwebtoken");


/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

router.get("/register", (req, res, next) => {
  res.json({
    code: 200,
    msg: "你好"
  })
})

router.post("/registers", async (req, res, next) => {

  let { username, userpwd, type } = req.body; //接收数据

  //加密操作
  let md5 = crypto.createHash("md5");
  userpwd = md5.update(userpwd).digest('hex');

  //把数据写入数据库(mongodb)
  let result = await userService.add([{ username, userpwd, usertype: type }])

  // 输出
  res.json({
    code: 200,
    msg: result
  })

})

router.post("/login", async (req, res, next) => {

  let { username, userpwd } = req.body;//接收数据

  //加密操作
  let md5 = crypto.createHash("md5");
  userpwd = md5.update(userpwd).digest("hex");


  let result = await userService.query({ username, userpwd });


  if (result.length) {

    let info = result[0];//用户信息

    let obj = { username: info.username, userid: info._id, usertype: info.usertype };

    let token = jwt.sign(obj, "abc", { expiresIn: 1000 * 60 * 30 })


    res.json({
      code: 200,
      msg: "登录成功",
      token,
      menu: info.usertype == 1 ? [{ path: "leave", msg: "请假管理", component: "leave", name: 'leave' }, { path: "student", msg: "学生管理", component: "student", name: 'student' }] : [{ path: "addleave", msg: "请假页面", component: "addleave", name: 'addleave' }]
    })
  } else {
    res.json({
      code: 500,
      msg: "用户和密码不匹配"
    })
  }



})
module.exports = router;
